package GameMgrNode

import (
	"Player"

	"git.oschina.net/yangdao/goerl"
)

//GameMgrNode 游戏逻辑管理节点
type GameMgrNode struct {
	workNode        *goerl.Node
	runingGameNodes map[int64]*GameNode
}

//New 创建GameMgrNode
func New() *GameMgrNode {
	retNode := &GameMgrNode{
		runingGameNodes: make(map[int64]*GameNode),
	}
	retNode.workNode = goerl.NewNode(retNode.receiveHandler)
	<-goerl.Register("GameMgrNode", retNode.workNode)
	return retNode
}

//Start 启动GameMgrNode
func (gameMgrNode *GameMgrNode) Start() {
	gameMgrNode.workNode.Start()
}

func (gameMgrNode *GameMgrNode) receiveHandler(data interface{}) {
	tuple := data.([]interface{})
	msgHead := tuple[0].(string)
	switch msgHead {
	case ":req-add-new-player":
		gameMgrNode.setToFreeGameNode(tuple[1].(*Player.GamePlayer))
	}
}

func (gameMgrNode *GameMgrNode) setToFreeGameNode(player *Player.GamePlayer) {
	var freeNode *GameNode
	for _, gameNode := range gameMgrNode.runingGameNodes {
		if gameNode.CurPlayerNumber < gameNode.MaxPlayerNumber {
			freeNode = gameNode
		}
	}
	if freeNode == nil {
		freeNode = NewGameNode()
		freeNode.Start()
		gameMgrNode.runingGameNodes[freeNode.NodeID] = freeNode
	}
	goerl.Send(freeNode.workNode, []interface{}{":new-player", player})
	goerl.SendByName("LobbyNode", []interface{}{":GameMgrMail", ":res-add-new-player", player.SessID, freeNode.workNode})

}
